package com.example.helper2;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class home_card_database extends SQLiteOpenHelper {
    public home_card_database(Context context){
        super(context,"cardDB.db",null,1);
    }
    public void onCreate(SQLiteDatabase sqLiteDatabase){
        String sql = "create table cards(id integer primary key autoincrement," +
                "type varchar(20),title varchar(50),content varchar(200))";
        sqLiteDatabase.execSQL(sql);
    }
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int il){

    }
    // 添加一条数据
    public void adddata(SQLiteDatabase sqLiteDatabase,String type,String title,String content){
        ContentValues values = new ContentValues();
        values.put("type",type);
        values.put("title",title);
        values.put("content",content);
        sqLiteDatabase.insert("cards",null,values);
    }
    // 查找所有数据
    public List<HomeCardInfo> querydata(SQLiteDatabase sqLiteDatabase){
        Cursor cursor = sqLiteDatabase.query("cards",
                                            null,
                                            null,
                                            null,
                                            null,
                                            null,
                                            "id ASC");
        List<HomeCardInfo> list = new ArrayList<>();
        while (cursor.moveToNext()){
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String type = cursor.getString(1);
            String title = cursor.getString(2);
            String content = cursor.getString(3);
            list.add(new HomeCardInfo(id,type,title,content));
        }
        cursor.close();
        sqLiteDatabase.close();
        return list;
    }
    // 根据id的值查找数据
    public HomeCardInfo querydatabyid(SQLiteDatabase sqLiteDatabase, int position){
        HomeCardInfo cardInfo = null;
        Cursor cursor = sqLiteDatabase.query("cards",
                null,
                "id=?",
                new String[]{position+""},
                null,
                null,
                "id ASC");
        if (cursor.getCount() > 0){
            cursor.moveToFirst();
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String type = cursor.getString(1);
            String title = cursor.getString(2);
            String content = cursor.getString(3);
            cardInfo = new HomeCardInfo(id,type,title,content);
        }
        cursor.close();
        sqLiteDatabase.close();
        return cardInfo;
    }
}
